package lambdasinaction.chap11.v1;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Created by ThinkPad on 2017/8/28.
 */
public class ShopMain {
    public static void main(String[] args) {
        Shop shop = new Shop("BestShop");
        long start = System.nanoTime();
//        使用异步API查询商店,过去商品价格
        Future<Double> futurePrice = shop.getPriceAsync("my favorite product");
        long invocateionTime = ((System.nanoTime() - start) / 1_000_000);
        System.out.println("Invocation returned after " + invocateionTime
            + "msecs");
//        Do some more task,like quering other shops
        doSomethingElse();
//        While the price of the product is being calculated
//        double price = shop.getPrice("my favorite product");
        try {
//            从Future对象中读取价格,如果价格未知,会发生阻塞
            double price = futurePrice.get();
            System.out.printf("Price is %.2f%n",price);
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        long retrievalTime = ((System.nanoTime() - start) / 1_000_000);
        System.out.println("Price returned after " + retrievalTime + " msecs");
    }

    private static void doSomethingElse() {
        System.out.println("Doing something else...");
    }
}
